from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response

from celery_tasks.static_file.tasks import generate_static_sku_detail_html
from goods.models import SKUImage, SKU


class ImagesSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = "__all__"

    def create(self, validated_data):
        """保存图片"""
        # 3 建立fdfs客户端
        client = Fdfs_client(settings.FASTDFS_PATH)
        # self.context['requst'] 获取request对象
        file = self.context['request'].FILES.get('image')
        # 4 上传图片
        res = client.upload_by_buffer(file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
           raise serializers.ValidationError({'error':'图片上传失败'})

        # 保存图片表
        img = SKUImage.objects.create(sku=validated_data['sku'], image=res['Remote file_id'])
        generate_static_sku_detail_html.delay(img.sku.id)
        return img

    def update(self, instance, validated_data):
        """更新图片"""
        # 3 建立fdfs客户端
        client = Fdfs_client(settings.FASTDFS_PATH)
        # self.context['requst'] 获取request对象
        file = self.context['request'].FILES.get('image')
        # 4 上传图片
        res = client.upload_by_buffer(file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
           raise serializers.ValidationError({'error':'图片上传失败'})

        # 更新图片信息
        instance.image = res['Remote file_id']
        instance.save()
        generate_static_sku_detail_html.delay(instance.sku.id)
        return instance


class SKUSerializer(serializers.ModelSerializer):
    """获取SKU信息序列化器"""
    class Meta:
        model = SKU
        fields = ('id', 'name')